/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.wdullaer.materialdatetimepicker.common;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.RecycleItemProvider;

import java.util.HashMap;

/**
 * 一个可以根据position获取Component的RecycleItemProvider
 * 用来解决ListContainer.getComponentAt返回始终为null的问题
 *
 * @date 2021/07/29
 */
public abstract class RecycleItemProvider2 extends RecycleItemProvider {

    HashMap<Integer, Component> map = new HashMap();

    /**
     * 实现ListContainer的getComponentAt功能
     *
     * @param position 位置
     * @return {@link Component}
     */
    public Component getComponentAt(int position) {
        return map.get(position);
    }

    public int getComponentPosition(Component component) {
        for (Integer key : map.keySet()) {
            if (component == map.get(key)) {
                return key;
            }
        }
        return -1;
    }

    public abstract Component getComponent2(int position, Component convertComponent, ComponentContainer componentContainer);

    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        Component component = getComponent2(position, convertComponent, componentContainer);
        if (component == convertComponent) {
            int pos = getComponentPosition(convertComponent);
            if (pos >= 0) {
                map.remove(pos);
            }
        }
        map.put(position, component);
        return component;
    }
}